package com.morpheus.redis.lettuce.config;

import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

/**
 * Redis使用FastJson序列化
 * 
 * @author ruoyi
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer {
	private static final Logger LOGGER = LoggerFactory.getLogger(FastJson2JsonRedisSerializer.class);

	private final static ParserConfig defaultRedisConfig = new ParserConfig();
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	@SuppressWarnings("unused")
	private ObjectMapper objectMapper = new ObjectMapper();
	private Class<T> clazz = null;

	static {
		defaultRedisConfig.setAutoTypeSupport(true);
	}

	public FastJson2JsonRedisSerializer(Class<T> clazz) {
		super();
		this.clazz = clazz;
		defaultRedisConfig.addAccept(this.clazz.getName());
	}

	@Override
	public byte[] serialize(Object obj) throws SerializationException {
		if (obj == null) {
			return new byte[0];
		}
		// return JSON.toJSONString(t,
		// SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
		try {
			return JSON.toJSONBytes(obj, SerializerFeature.WriteClassName);
		} catch (Exception ex) {
			throw new SerializationException("Could not serialize: " + ex.getMessage(), ex);
		}
	}

	@Override
	public Object deserialize(byte[] bytes) throws SerializationException {
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		String str = new String(bytes, DEFAULT_CHARSET);
		//LOGGER.info("FastJson2JsonRedisSerializer.deserialize() str={}", str);
		Object result = JSON.parseObject(str, Object.class, defaultRedisConfig);
		if (result instanceof String) {
			return result;
		} else if (result != null && this.clazz.isAssignableFrom(result.getClass())) {
			return (T) result;
		}
		return null;
	}

	public void setObjectMapper(ObjectMapper objectMapper) {
		Assert.notNull(objectMapper, "'objectMapper' must not be null");
		this.objectMapper = objectMapper;
	}

	protected JavaType getJavaType(Class<?> clazz) {
		return TypeFactory.defaultInstance().constructType(clazz);
	}
}
